import time

import allure
import yaml
from selenium.common import NoSuchElementException
from selenium.webdriver.common.by import By

from page.home_page import HomePage
from utils.logger import logger


class LoginPage(HomePage):
    _Username = (By.CSS_SELECTOR, "[name='username']")
    _Password = (By.CSS_SELECTOR, "[name='password']")
    _LOGIN = (By.CSS_SELECTOR, ".login-btn")

    def login(self, user='15632114481', password='Geng_15632114481'):
        logger.info(f"登录用户：{user}")
        with allure.step(f"登录用户：{user}"):
            self.find_and_send(user, *self._Username)
            self.find_and_send(password, *self._Password)
            self.set_time(10)
            self.find_and_click(*self._LOGIN)
        logger.info(f"用户 {user} 登录成功")
        return self

    def save_cookie(self):
        logger.info("保存cookie信息")
        time.sleep(3)
        cookie = self._driver.get_cookies()
        with open('../data/cookies.yaml', 'w', encoding='utf-8') as f:
            yaml.safe_dump(data=cookie, stream=f)
        return self

    def get_cookie(self):
        logger.info("获取cookie信息")
        # 读取文件中的cookie
        with open('../data/cookies.yaml', 'r', encoding='utf-8') as f:
            cookie = yaml.safe_load(f)
        # 植入cookie信息
        for i in cookie:
            self._driver.add_cookie(i)
        self._driver.get(self._BASE_URL)
        return self


